<template>
  <div class="card col_center m10 p10">
    <label class="title">串口设置</label>
    <div class="row_center mt">
      <el-select v-model="ctx.name" class="ml" style="width: 100px;">
        <el-option
          v-for="(item, index) in ctx.ports"
          :key="index"
          :label="item"
          :value="item"
        />
      </el-select>
      <el-button @click="onClickGetPorts" class="ml" type="primary">刷新</el-button>
    </div>
    <el-button @click="onClickOpen" class="mt" type="primary" style="width: 100px;">{{ ctx.conn_text }}</el-button>
  </div>
</template>


<script setup lang="ts">
import { reactive } from 'vue';
import conn from '../service/conn';
import { dialog } from '../service/ui';


interface Ctx {
  ports: string[],
  name: string,
  conn_text: string,
}

const ctx = reactive<Ctx>({
  ports: [],
  name: '',
  conn_text: '打开',
});

async function update() {
  try {
    const ret = await conn.conn_is_open();
    if (ret) {
      ctx.conn_text = '关闭';
    } else {
      ctx.conn_text = '打开';
    } 

  } catch (msg) {
    dialog.err(msg);
  }
}

async function onClickGetPorts() {
  try {
    ctx.ports = await conn.avaliable_port_names();
    if (ctx.ports.length == 0) {
      //dialog.err('没有串口');
    } else {
      ctx.name = ctx.ports[0];
    }
  } catch (msg) {
    dialog.err(msg);
  }
}

async function onClickOpen() {
  try {
    const ret = await conn.conn_is_open();
    if (ret) {
      await conn.conn_close();
    } else {
      if (ctx.name.length == 0) {
        dialog.err('没有串口');
        return;
      }
      await conn.conn_open(ctx.name);
    }
    await update();
  } catch (msg) {
    dialog.err(msg);
  }
}


onClickGetPorts();
update();

</script>
